<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import router from '@/router';
import { useTokenStore } from '@/stores/mytoken'
import { login,register } from '@/api/users'

const store = useTokenStore()
const route = useRoute()
let isLogin = ref(false)
let btnText = computed(() => {
  return isLogin.value ? '注册' : '登录';
})
const ruleFormRef = ref<FormInstance>();

const checkUname = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("Please input the uname"));
  }
  setTimeout(() => {
    if (!String) {
      callback(new Error("Please input digits"));
    } else {
      if (value < 18) {
        callback(new Error("uname must be greater than 18"));
      } else {
        callback();
      }
    }
  }, 1000);
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (ruleForm.checkPass !== "") {
      if (!ruleFormRef.value) return;
      // ruleFormRef.value.validateField("checkPass", () => null);
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入再次密码"));
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  uname: "18201288771@ww.com",
  pass: "111111",
  checkPass: "111111",
  realname: "",
  dept: ""
});

const rules = reactive<FormRules<typeof ruleForm>>({
  uname: [{ validator: checkUname, trigger: "blur" }],
  pass: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (isLogin.value) {
    register(ruleForm)
  } else {
    // ElMessage.success('登录成功！')
    if (!formEl) return;
    formEl.validate((valid) => {
      if (valid) {
        console.log("submit!");
        // router.push('/')
      } else {
        console.log("error submit!");
        return false;
      }
    });
    const data = await login(ruleForm).then((res: any) => {
      if (!res.data.accessToken) {
        ElMessage.error('登录信息有误')
        throw new Error('登录信息有误')
      }
      return res.data
    }).catch(()=>{
      ElMessage.error('用户名或密码有误')
    })
    
    //保存token
    store.saveToken(data)
    router.push((route.query.redirect as string) || "/")
    
  }

};
</script>

<template>
  <div class="switch">
    <el-button link type="primary" size="small" @click="isLogin=true">注册</el-button>
    <el-button link type="primary" size="small" @click="isLogin=false">登录</el-button>
  </div>
  <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
    <el-form-item label="用户名" prop="uname">
      <el-input v-model.number="ruleForm.uname" />
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass" v-if="isLogin">
      <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button id="submitbtn" type="primary" @click="submitForm(ruleFormRef)">{{ btnText }}</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
.el-form {
  width: 100vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  left: 0;
  top: 40%;

  .el-form-item {
    .el-input {
      width: 20vw;
    }

    #submitbtn {
      width: 20vw;
      border-radius: 0.4vw;
    }
  }

}
</style>
